package com.yanqu.road.server.gameplayer.module.player;

import com.yanqu.road.entity.config.goods.GoodsInfo;
import com.yanqu.road.entity.enums.eLogMoneyType;
import com.yanqu.road.entity.log.LogCouponTrigger;
import com.yanqu.road.entity.player.UserCouponItem;
import com.yanqu.road.logic.bussiness.recharge.CouponBussiness;
import com.yanqu.road.logic.config.ChannelConfig;
import com.yanqu.road.logic.pb.CouponPb;
import com.yanqu.road.pb.recharge.CouponProto;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.base.GeneralModule;
import com.yanqu.road.server.manger.config.GoodsMgr;
import com.yanqu.road.server.manger.log.AutoLogMgr;
import com.yanqu.road.server.manger.thirdparty.ThirdPartyMgr;
import com.yanqu.road.server.protocol.Protocol;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

/**
==============================================
 *优惠券模块
==============================================
* 作者：zrq
* 时间：2023/4/18
**/
public class CouponModule extends GeneralModule {
    private AtomicLong maxCouponItemId;
    private Map<Long, UserCouponItem> couponItemMap = new ConcurrentHashMap<>();
    private int couponUsedCount = 0;   //优惠券使用次数
    public CouponModule(GamePlayer player) {
        super(player);
    }

    @Override
    public boolean loadData() {
        long maxId = CouponBussiness.getMaxItemId(player.getUserId());
        maxCouponItemId = new AtomicLong(maxId);
        couponItemMap = CouponBussiness.getUserCouponItemMap(player.getUserId(), System.currentTimeMillis());
        couponUsedCount = CouponBussiness.getCouponUsedCount(player.getUserId());
        return true;
    }

    @Override
    public boolean afterLoadData() {
        return true;
    }

    @Override
    public boolean saveData() {
        for(UserCouponItem data : couponItemMap.values()){
            if(data.isInsertOption()){
                CouponBussiness.addUserCouponItem(data);
            }else if(data.isUpdateOption()){
                CouponBussiness.updateUserCouponItem(data);
            }
        }
        return true;
    }

    @Override
    public void loginSendMsg() {

    }

    @Override
    public void afterLogin() {
        if(null != couponItemMap){
            syncCouponList(new ArrayList<>(couponItemMap.values()), true);
        }
    }

    public void syncCoupon(UserCouponItem data){
        if(null != data){
            List<UserCouponItem> syncList = new ArrayList<>();
            syncList.add(data);
            syncCouponList(syncList, false);
        }
    }

    public void syncCouponList(List<UserCouponItem> dataList, boolean isLogin){
        List<UserCouponItem> filterList = new ArrayList<>();
        if(null != dataList){
            for(UserCouponItem data : dataList){
                if(GoodsMgr.canUseCoupon(data, player.getPhonePlatform())){
                    filterList.add(data);
                }
            }
        }
        CouponProto.CouponItemListMsg.Builder syncMsg = CouponPb.parseCouponItemListMsg(filterList);
        if(isLogin){
            player.sendPacket(Protocol.U_COUPON_ITEM_LIST, syncMsg);
        }else {
            player.sendPacket(Protocol.U_COUPON_ITEM_SYNC, syncMsg);
        }
    }

    /**
    * 描述：增加优惠券道具
    * 作者：zrq
    * 时间：2023/4/18
    * 参数：

    * 返回值：
    **/
    public List<UserCouponItem> addCouponItem(int goodsId, long count, eLogMoneyType master, eLogMoneyType son){
        List<UserCouponItem> dataList = new ArrayList<>();
        for(int i = 0; i < count; i++){
            UserCouponItem data = addCouponItem(goodsId, master, son);
            if(null != data){
                dataList.add(data);
            }
        }
        return dataList;
    }

    /**
    * 描述：增加优惠券
    * 作者：zrq
    * 时间：2023/4/18
    * 参数：

    * 返回值：
    **/
    public synchronized UserCouponItem addCouponItem(int goodsId, eLogMoneyType master, eLogMoneyType son){
        long nowTime = System.currentTimeMillis();
        if(ChannelConfig.COUPON_ONLY_ONE_SWITCH == 1) {
            for (UserCouponItem data : couponItemMap.values()) {
                if (data.getGoodsId() == goodsId && !data.isUse() && data.getExpirationTime() > nowTime) {//已经有同类型代金券了
                    return null;
                }
            }
        }
        UserCouponItem data = new UserCouponItem();
        data.setItemId(maxCouponItemId.incrementAndGet());
        data.setUserId(player.getUserId());
        data.setGoodsId(goodsId);
        data.setUse(false);
        data.setGetTime(nowTime);
        long addTime = 0;
        GoodsInfo goodsInfo = GoodsMgr.getGoodsById(goodsId);
        if(null != goodsInfo && GoodsMgr.isCouponItem(goodsId)){
            long param3 = goodsInfo.getParamList().get(2).longValue();          //有效分钟数
            addTime = param3 * 60 * 1000;
        }
        data.setExpirationTime(nowTime + addTime);
        data.setInsertOption();
        couponItemMap.put(data.getItemId(), data);
        syncCoupon(data);
        //代金券上报
        String goodsName = GoodsMgr.getLocalGoodsName(goodsId, player.getLanguage());
        int potential = player.getModule(PotentialModule.class).getPotential();
        ThirdPartyMgr.couponReport(player.getUserId(), player.getUserInfo().getPlatformUserId(), goodsId, goodsName, 1,
                getCouponItemTotalCount(), getCouponItemCount(), master.getName(), son.getName(), player.getTitleId(), potential,
                new Date(), 0, "", "0", "", new Date());
        //日志
        AutoLogMgr.add(new LogCouponTrigger(player.getUserId(), data.getItemId(), goodsId, getCouponItemTotalCount(), getCouponItemCount(),
                player.getTitleId(), potential, son.getValue()));
        return data;
    }

    public UserCouponItem getUserCouponItem(long couponItemId){
        return couponItemMap.get(couponItemId);
    }

    public long getCouponItemTotalCount(){
        return maxCouponItemId.longValue();
    }

    public long getCouponItemCount(){
        long count = 0;
        for(UserCouponItem data: couponItemMap.values()){
            if(!data.isUse() && data.getExpirationTime() > System.currentTimeMillis()){
                count++;
            }
        }
        return count;
    }

    public int getCouponUsedCount() {
        return couponUsedCount;
    }

    public void addCouponUsedCount() {
        this.couponUsedCount++;
    }
}
